var counter = 0;
var highestIdProcessed = -1;
var currentWord;
var player;
var needsToBeSaved = false;
var ended = false;

function keyevent(evt){
	if (evt.keyCode == 39){
		// round to two decimal places and save
		var time = Math.round(player.currentTime * 100) / 100;
		times.push(time);
		currentWord.style.fontWeight = "normal";
		selectNextWord(currentWord);
		needsToBeSaved = true;
	}
	else if (evt.keyCode == 80){
		if (playing){
			pause();
		}
		else{
			play();			
		}
	}
	else if (evt.keyCode == 70){
		alert(times);
	}
}

var playing = false;
function play(){
	var begin = document.getElementById("begin");
	begin.disabled=true;
	if (times == null || times.length == 0){
		times.push(.1);
		selectNextWord();
	}
	begin.innerHTML = "Play";
	var pause = document.getElementById("pause");
	pause.disabled=false;
	playing = true;
	player.play();
	player.playbackRate = .5;
}

function pause(){
	var begin = document.getElementById("begin");
	begin.disabled=false;
	var pause = document.getElementById("pause");
	pause.disabled=true;
	player.pause();
	playing = false;
	if (needsToBeSaved){
		enableSaveButtons();
	}
}

var configed = false;
function configMediaPlayer(){
	if (!configed){
		configed = true;
//		alert("configMediaPlayer()");
		if (times.length > 0){
			var lastIndexToBeRecorded = times.length - 1;
			//alert(times[lastIndexToBeRecorded])
		//	alert("w" + lastIndexToBeRecorded);
			counter = lastIndexToBeRecorded + 1;
			
			currentWord =  document.getElementById("w" + lastIndexToBeRecorded);
	//		alert(lastWord);
			if (currentWord != null){
				currentWord.style.fontWeight = "bold";
				player.currentTime= times[lastIndexToBeRecorded];
			}
		}
	}
}

function verifyBrowserCompatibility(){
	var agent = navigator.userAgent;
	///user/readings/demoSound.jsp?id=6
	if ( agent.indexOf("Safari") == -1 || agent.indexOf("Chrome") != -1){
		checkin();
		alert("The sound integration task requires the use of Safari at this time.");
		window.location = "/eng/volunteering.html"
		return false;
	}
	return true;
}

function init(){
	verifyBrowserCompatibility();
	player =  document.getElementsByTagName('audio')[0];;
	player.addEventListener("canplaythrough", function() { configMediaPlayer() }, true);
	player.addEventListener("ended", function() { onEndMediaPlayer() }, true);	
}


function onEndMediaPlayer(){
	ended = true;
	pause();
}
function selectNextWord(){
	highestIdProcessed = counter;
	var id = "w"+ counter++;
	currentWord = document.getElementById(id);
	if (currentWord != null){ //verify we haven't gotten to the end of the documents
		currentWord.style.fontWeight = "bold";
	}
}

function shiftTimes(arrayToCopy, subtractBy){
	size = arrayToCopy.length;
	newArray = new Array()
	for (y = 0; y < arrayToCopy.length; y++){
		var newValue = arrayToCopy[y] - Number(subtractBy);
		newValue = Math.round(newValue * 100) / 100;
		//alert(newValue);
		newArray.push(newValue);

	}
	return newArray;
}

/*function saveExit(){
	save2();
	//window.location="/user/readings/sound2.jsp?id=" + id;
}*/

function save(){
	if (ended){
		var newTimes = shiftTimes(times, .1);
		saveTimes(newTimes);
	}
	else{
		saveTimes(times);
	}
}
function disableSaveButtons(){
	var saveButton = document.getElementById("save");
	saveButton.disabled=true;
	//var continueButton = document.getElementById("continue");
	//continueButton.disabled=false;
}
function enableSaveButtons(){
	var saveButton = document.getElementById("save");
	saveButton.disabled=false;
}

function saveTimes(timesToSave){
	var message = document.getElementById("message");
	message.innerHTML = "Saving...";
	$.ajax({
  type: 'POST',
  url: "/user/readings/sound_save.jsp",
  data: {id: id, times: timesToSave.toString(), highestIdProcessed: highestIdProcessed},
  success: function(msg) {
	//var saveButton = document.getElementById("save_button");
	disableSaveButtons();
	var message = document.getElementById("message");
	message.innerHTML = "";
	//saveButton.disabled = true;
  },
  error:function(request,error){ alert("An error occurred while saving: " + error); },
  dataType: "xml"
});	
	needsToBeSaved = false;
}

function checkinAndExit(){
	var message = document.getElementById("message");
	message.innerHTML = "Exiting...";
	var exitButton = document.getElementById("exit");
	exitButton.disabled = true;
	$.ajax({
  type: 'POST',
  url: "/user/readings/checkin_sound.jsp",
  data: {id: id},
  success: function(msg) {
	window.location = "/user/readings/reading_view.jsp?id=" + id;
  },
  error:function(request,error){ alert("An error occurred while saving: " + error); },
  dataType: "xml"
});	
}

function continueOn(){
	window.location = "/user/readings/sound2.jsp?id=" + id;
}

function tryToExit(){
	if (needsToBeSaved){
		$("#confirmation").dialog({
			modal: true,
			title: useroptionString,
			buttons: { 
			"Cancel": function() { $(this).dialog("close"); },
			"Exit": function() { $(this).dialog("close"); checkinAndExit() }
			}
		});
	}
	else{
		checkinAndExit();
	}
}
